/*
 * 导入excel方法
 * file - 导入的excel文件
 * range - 读取excel的初始行
 * tVariable - 导入的表头名对应的属性名
 */
import { Message } from "element-ui";
const importExcel = function(file, range, tVariable) {
  return new Promise(function(resolve, reject) {
    var f = file.raw;
    var reader = new FileReader();
    FileReader.prototype.readAsBinaryString = function(f) {
      var binary = "";
      var wb; // 读取完成的数据
      var outdata;
      var reader = new FileReader();
      reader.onload = function(e) {
        var bytes = new Uint8Array(reader.result);
        var length = bytes.byteLength;
        for (var i = 0; i < length; i++) {
          binary += String.fromCharCode(bytes[i]);
        }
        var XLSX = require("xlsx");
        wb = XLSX.read(binary, {
          type: "binary"
        });
        const sheet2JSONOpts = {
          range: range, // 填写0则表示为A1为变量名
          defval: "" // 给defval赋值为空的字符串
        };
        outdata = XLSX.utils.sheet_to_json(
          wb.Sheets[wb.SheetNames[0]],
          sheet2JSONOpts
        ); // outdata就是你想要的东西
        const outdataList = []; // 最终输出值
        for (let i = 0; i < outdata.length; i++) {
          const arr = []; // excel每行的值
          const obj = {}; // 定义每一行 属性名：属性值
          for (let key in outdata[i]) {
            arr.push(outdata[i][key]);
          }
          for (let j = 0; j < tVariable.length; j++) {
            obj[tVariable[j]] = arr[j];
          }
          console.log(arr);
          outdataList.push(obj); // 拼接成对象数组
        }

        Message.success("导入表格成功");
        if (outdataList.length > 1000) {
          reject("导入数据超过500行");
        } else {
          resolve(outdataList);
        }
      };
      reader.readAsArrayBuffer(f);
    };
    reader.readAsBinaryString(f);
  });
};
export default importExcel;
